package com.tduck.cloud.report.data.db;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.toolkit.JdbcUtils;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.pool.HikariPool;
import lombok.Builder;

@Builder
public class HikariPoolBuilder extends HikariConfig {

    public HikariPool dataSource(String url, String username, String password) {
        // 从url中截取是什么数据库
        DbType dbType = JdbcUtils.getDbType(url);
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setJdbcUrl(url);
        hikariConfig.setUsername(username);
        hikariConfig.setPassword(password);
        hikariConfig.setDriverClassName(getDriverClass(dbType));
        hikariConfig.setConnectionTimeout(getConnectionTimeout());
        hikariConfig.setValidationTimeout(getValidationTimeout());
        hikariConfig.setIdleTimeout(getIdleTimeout());
        hikariConfig.setMaxLifetime(getMaxLifetime());
        hikariConfig.setMaximumPoolSize(getMaximumPoolSize() > 0 ? getMaximumPoolSize() : 15);
        hikariConfig.setMinimumIdle(getMinimumIdle() > 0 ? getMinimumIdle() : 5);
        return new HikariPool(hikariConfig);
    }


    public static String getDriverClass(DbType dbType) {
        String driverClass;
        switch (dbType) {
            case MYSQL:
                driverClass = "com.mysql.cj.jdbc.Driver";
                break;
            case ORACLE:
                driverClass = "oracle.jdbc.driver.OracleDriver";
                break;
            // 添加其他数据库的驱动类
            default:
                throw new IllegalArgumentException("Unsupported database type: " + dbType);
        }
        return driverClass;
    }
}
